<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\AttrClass;
use app\admin\model\AttrGroupClass;
use app\admin\model\SchoolClassGoods;
use app\common\controller\Backend;
use think\Db;

/**
 * 管理员管理
 *
 * @icon fa fa-circle-o
 */
class Grade extends Backend
{
    
    /**
     * Grade模型对象
     * @var \app\admin\model\Grade
     */
    protected $model = null;
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Grade;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','attr']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /*
     * 年级/班级管理
     * */
    public function class()
    {
        $admin = Admin::get($this->auth->id);
        $class = $admin->attr;

        //规格组
        $attr_group_list = [];
        if ($class) {
            $attr_data = json_decode($class, true);
            foreach ($attr_data as $i => $attr_data_item) {
                foreach ($attr_data[$i]['attr_list'] as $j => $attr_list) {
                    $attr_group = Db::name('attr_group_class')
                        ->where('id','in',DB::name('attr_class')->where('id', $attr_data[$i]['attr_list'][$j]['attr_id'])->distinct(true)->column('attr_group_id'))
                        ->find();
                    if ($attr_group) {
                        $in_list = false;
                        foreach ($attr_group_list as $k => $exist_attr_group) {
                            if ($exist_attr_group['attr_group_name'] == $attr_group['attr_group_name']) {
                                $attr_item = [
                                    'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                    'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                                ];
                                if (!in_array($attr_item, $attr_group_list[$k]['attr_list'])) {
                                    $attr_group_list[$k]['attr_list'][] = $attr_item;
                                }
                                $in_list = true;
                            }
                        }
                        if (!$in_list) {
                            $attr_group_list[] = [
                                'attr_group_id' => $attr_group['id'],
                                'attr_group_name' => $attr_group['attr_group_name'],
                                'attr_list' => [
                                    [
                                        'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                        'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                                    ],
                                ],
                            ];
                        }
                    }
                }
            }
        }

        $this->assign('attr_group_list', $attr_group_list);

        return $this->view->fetch();
    }

    public function edit($ids = "")
    {
        $admin = Admin::get($this->auth->id);
        $class = $admin->attr;
        //规格组
        $attr_group_list = [];
        if ($class) {
            $attr_data = json_decode($class, true);
            foreach ($attr_data as $i => $attr_data_item) {
                foreach ($attr_data[$i]['attr_list'] as $j => $attr_list) {
                    $attr_group = Db::name('attr_group_class')
                        ->where('id','in',DB::name('attr_class')->where('id', $attr_data[$i]['attr_list'][$j]['attr_id'])->distinct(true)->column('attr_group_id'))
                        ->find();
                    if ($attr_group) {
                        $in_list = false;
                        foreach ($attr_group_list as $k => $exist_attr_group) {
                            if ($exist_attr_group['attr_group_name'] == $attr_group['attr_group_name']) {
                                $attr_item = [
                                    'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                    'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                                ];
                                if (!in_array($attr_item, $attr_group_list[$k]['attr_list'])) {
                                    $attr_group_list[$k]['attr_list'][] = $attr_item;
                                }
                                $in_list = true;
                            }
                        }
                        if (!$in_list) {
                            $attr_group_list[] = [
                                'attr_group_name' => $attr_group['attr_group_name'],
                                'attr_list' => [
                                    [
                                        'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                        'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                                    ],
                                ],
                            ];
                        }
                    }
                }
            }
        }

        $attr_data = [
            'attr_group_list' => $attr_group_list,
            'attr' => $class
        ];

        if ($this->request->isPost()) {
            $params = $this->request->post();
//            dump($params);exit();
            if ($params) {
                $attr = $params['attr'];
                if ($attr) {
                    $new_attr = [];
                    foreach ($attr as $i => $item) {

                        $new_attr_item = [
                            'attr_list' => [],
                        ];

                        $attr_group_model = AttrGroupClass::get(['store_id' => 1, 'attr_group_name' => $item['attr_group_name'], 'is_delete' => 0]);
                        if (!$attr_group_model) {
                            $attr_group_model = new AttrGroupClass();
                            $attr_group_model->attr_group_name = $item['attr_group_name'];
                            $attr_group_model->store_id = 1;
                            $attr_group_model->is_delete = 0;
                            $attr_group_model->save();
                        }

                        foreach ($item['attr_list'] as $a) {
                            $attr_model = AttrClass::get(['attr_group_id' => $attr_group_model->id, 'attr_name' => $a['attr_name'], 'is_delete' => 0]);
                            if (!$attr_model) {
                                $attr_model = new AttrClass();
                                $attr_model->attr_name = $a['attr_name'];
                                $attr_model->attr_group_id = $attr_group_model->id;
                                $attr_model->is_delete = 0;
                                $attr_model->save();
                            }
                            $new_attr_item['attr_list'][] = [
                                'attr_id' => $attr_model->id,
                                'attr_name' => $attr_model->attr_name,
                            ];
                        }
                        $new_attr[] = $new_attr_item;
                    }
                    $admin->attr = json_encode($new_attr, JSON_UNESCAPED_UNICODE);
                    if ($admin->save() !== false) {
                        $this->success('修改成功');
                    } else {
                        $this->error('修改失败, 请重试!');
                    }
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));

        }

        $this->view->assign("attr_data", json_encode($attr_data));

        return $this->view->fetch();
    }

    public function look()
    {
        $params = $this->request->get();
        $add_attr = $params['add_attr'];

        //获取年级_id
        $class = Db::name('attr_class')->where(['id' => ['in', $add_attr]])->distinct(true)->field('id, attr_name, attr_group_id')->select();
        $grade_id = [];
        foreach ($class as $k => $v) {
            $grade_id[$k] = $v['attr_group_id'];
        }

        //年级
        $grade = Db::name('attr_group_class')->where(['id' => ['in', $grade_id]])->field('id, attr_group_name')->select();

        foreach ($grade as $k=>&$g) {
            foreach($class as $kc=>$c) {
                if ($c['attr_group_id'] == $g['id']) {
                    $goods_id = SchoolClassGoods::where(['attr_id' => $c['id'], 'school_admin_id' => $this->auth->id])->column('goods_id');
                    $c['goods'] = Db::name('goods')->where(['id' => ['in', $goods_id], 'is_delete' => 0])->field('id, name, cover_pic, price')->select();
                    $g['class'][] = $c;
                }
            }
        }

//        dump($grade);exit();

        $this->view->assign("data", $grade);

        return $this->view->fetch();

    }

}
